import { ManageUser } from './../../interface/interface';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserManagementService } from '../../user-management.service';
import { ToolsService, NotificationService, MessagesService } from 'app/shared/service';
import { CompileShallowModuleMetadata } from '@angular/compiler';
import { NzMessageService, NzModalService, NzFormatEmitEvent, NzTreeComponent } from 'ng-zorro-antd';
import { sha256 } from 'js-sha256';
import { ChangePasswordBoxService } from '../../../../layouts/header/change-password-box/change-password-box.service';
import { LoginService } from 'app/auth/login.service';
import { ZoomInOutline } from '@ant-design/icons-angular/icons/public_api';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-add-user',
    templateUrl: './add-user.component.html',
    styleUrls: ['./add-user.component.css']
})
export class AddUserComponent implements OnInit {
    private _optionList = [];
    isOkLoading = false;
    data = '';
    isEditable = false;
    userName = '';
    defaultCheckedKeys = [];
    defaultSelectedKeys = [];
    defaultExpandedKeys = [];
    zoneList = [];
    @ViewChild('nzTree') nzTree: NzTreeComponent;

    @Input() visible = false;
    @Input() title = '';
    @Input() userId = '';
    @Input() selectionList: any;
    @Input() createTime: any;
    @Output() visibleChange = new EventEmitter<boolean>();
    @Output() manageUserChange = new EventEmitter<void>();
    pwd: string;
    // 初始化表单
    @Input()
    set manageUser(value: ManageUser) {
        if (value) {
            this.pwd = value.user_Pwd;
            this.formDataInit(value);
        }
    }

    @Input() roleOptions = [];
    @Input() listOfOption = [];
    @Input() zoneAssignment = [];
    @Input() selectZoneAssignment = [];
    userInfoForm: FormGroup;
    isShowZone = false;
    constructor(
        private fb: FormBuilder,
        private http: HttpClient,
        private UMService: UserManagementService,
        private tools: ToolsService,
        private message: NzMessageService,
        private msg: NotificationService,
        private modalService: NzModalService,
        private changePasswordBoxService: ChangePasswordBoxService,
        public ls: LoginService,
        private translate: TranslateService
    ) {
        this.userInfoForm = this.fb.group({
            userId: [null, Validators.required],
            user_Name: [null, Validators.required],
            user_Pwd: [null, Validators.required],
            organization: [null, Validators.required],
            userRole: [null, Validators.required]
        });
    }
    private formDataInit(value: ManageUser) {
        this.userInfoForm.setValue(value);
    }

    close() {
        this.visible = false;
        this.visibleChange.emit(this.visible);
    }

    // cancel 按钮
    handleCancel() {
        this.close();
    }
    nzEvent(event: NzFormatEmitEvent): void {
        this.zoneList = [];
        const tempZoneList = this.nzTree.getCheckedNodeList();
        tempZoneList.forEach(zone => {
            this.zoneList.push({
                id: zone.origin.id ? JSON.parse(zone.origin.id) : 0,
                userId: zone.origin.userId ? zone.origin.userId : 0,
                vnqn_zone_id: zone.origin.key ? JSON.parse(zone.origin.key) : '',
                permanent: 1
            });
        });
    }

    submitForm(): void {
        // tslint:disable-next-line:forin
        for (const i in this.userInfoForm.controls) {
            if (this.userInfoForm.controls.hasOwnProperty(i)) {
                this.userInfoForm.controls[i].markAsDirty();
                this.userInfoForm.controls[i].updateValueAndValidity();
            }
        }

        const value = this.tools.isClone(this.userInfoForm.value);
        const userRole = this.roleOptions.find(item => item.userRole_Id === value.userRole);
        value.userRole = userRole;
        const userOrganization = this.listOfOption.find(item => item.organization_Name === value.organization);
        value.organization = {
            organization_Id: userOrganization.organization_Id,
            organization_Name: userOrganization.organization_Name
        };
        value.userZoneRel = this.zoneList;
        if (this.title === 'Add_User') {
            value.user_Pwd = sha256('123456'); // 默认密码
        }
        // if (this.pwd !== value.user_Pwd) {
        // this.userInfoForm.get('')
        // }
        if (value.userId === 0) {
            // 新建
            // value.user_Name = value.user_Name.toLowerCase();
            this.UMService.createUserInfo(value).subscribe(res => {
                this.isOkLoading = false;
                if (res.code === '000000') {
                    this.manageUserChange.emit();
                    // this.message.create('success', res.msg);
                    this.msg.notify({ type: 'success', path: 'UserManagement.ManageUser.createSuccess_notify' });
                    this.visible = false;
                    this.visibleChange.emit(this.visible);
                } else if (res.code === '900006') {
                    this.msg.notify({ type: 'warning', path: 'UserManagement.ManageUser.createRepeat_notify' });
                }
                // else {
                //     this.msg.notify({ type: 'warning', path: 'UserManagement.ManageUser.createFailed_notify' });
                // }
            });
        } else {
            const tempZoneList = [];
            this.zoneAssignment.forEach(zone => {
                if (zone.checked) {
                    tempZoneList.push({
                        userId: value.userId,
                        vnqn_zone_id: zone.key,
                        id: 0,
                        permanent: 1
                    });
                }
            });
            const queryData = {
                organization: value.organization,
                userId: value.userId,
                userRole: value.userRole,
                user_Pwd: value.user_Pwd,
                // user_Name: this.userName.toLowerCase(),
                user_Name: this.userName,
                createTime: this.createTime,
                userZoneRel: tempZoneList
            };
            this.UMService.updateUserInfo(queryData).subscribe(res => {
                this.isOkLoading = false;
                if (res.code === '000000') {
                    this.manageUserChange.emit();
                    this.visible = false;
                    this.visibleChange.emit(this.visible);
                } else {
                    this.msg.notify({ type: 'warning', path: 'UserManagement.ManageUser.createFailed_notify' });
                }
            });
        }
    }
    // 重置密码
    showResetPassword() {
        const tempTranslate = [
            { title: 'UserManagement.ManageUser.Do you Want to reset your password' },
            { title: 'UserManagement.ManageUser.Your password will reset to 123456' },
            { title: 'UserManagement.ManageUser.OK' },
            { title: 'UserManagement.ManageUser.NO' }
        ];
        tempTranslate.forEach(item => {
            this.translate.get(item.title).subscribe((res: string) => {
                item.title = res || '';
            });
        });
        this.modalService.confirm({
            nzTitle: '<i>' + tempTranslate[0].title + '?</i>',
            nzContent: '<b>' + tempTranslate[1].title + '</b>',
            nzOkText: tempTranslate[2].title,
            nzOnOk: () => {
                const nowData = new Date();
                const timeDe = nowData.getTime();
                const newPwd = sha256('123456');
                const param = {
                    userName: this.userName.toLowerCase(),
                    token: sha256(this.userName.toLowerCase() + this.pwd + timeDe).toUpperCase(),
                    time: timeDe,
                    newPwd
                };
                this.pwd = null;
                this.userInfoForm.get('user_Pwd').setValue(null);
                this.changePasswordBoxService.changePwd(param).subscribe(res => {
                    if (res['code'] === '000000') {
                        // 登出
                        this.msg.notify({ type: 'success', path: 'UserManagement.ManageUser.reset_password_success' });
                        this.pwd = newPwd;
                        this.userInfoForm.get('user_Pwd').setValue(newPwd);
                        // this.ls.logOut();
                    } else {
                        this.message.warning(res['msg']);
                    }
                });
            },
            nzCancelText: tempTranslate[3].title
        });
    }
    ngOnInit() {
        if (this.title !== 'Add_User') {
            for (let item = 0; item < this.roleOptions.length; item++) {
                if (this.roleOptions[item].userRole_Id === this.userInfoForm.value.userRole) {
                    this.isShowZone =
                        this.roleOptions[item].methodAccess.filter(isZone => isZone.accessId === 94).length > 0 ? true : false;
                }
            }
        } else {
            for (let item = 0; item < this.roleOptions.length; item++) {
                if (this.roleOptions[item].userRole_Id === parseInt(localStorage.getItem('role_id'))) {
                    this.isShowZone =
                        this.roleOptions[item].methodAccess.filter(isZone => isZone.accessId === 94).length > 0 ? true : false;
                }
            }
        }
        this.zoneAssignment.forEach(zone => {
            this.translate.get('UserManagement.ManageUser.' + zone.name).subscribe((res: string) => {
                zone.title = res;
            });
            (zone.key = JSON.parse(zone.value)), (zone.isLeaf = true);
        });
        const tempSelectList = this.selectZoneAssignment.filter(zone => zone.permanent === 1).map(zone => zone.vnqn_zone_id);
        this.defaultCheckedKeys = [];
        this.defaultSelectedKeys = [];
        this.defaultCheckedKeys = tempSelectList;
        this.defaultSelectedKeys = tempSelectList;
        // this.zoneAssignmen.forEach
        // 先拿到userName，不然userName框禁止后拿不到
        this.userName = this.userInfoForm.value.user_Name;
        // 编辑时禁止编辑用户名
        if (this.userInfoForm.value.userId !== 0) {
            for (const key in this.userInfoForm.controls) {
                if (this.userInfoForm.controls.hasOwnProperty(key)) {
                    this.userInfoForm.controls.user_Name.disable();
                }
            }
        }
    }
}
